package com.kamistoat.rocketmqlearning.delayMsg;

import com.kamistoat.rocketmqlearning.common.R;
import org.apache.rocketmq.client.exception.MQBrokerException;
import org.apache.rocketmq.client.exception.MQClientException;
import org.apache.rocketmq.client.producer.DefaultMQProducer;
import org.apache.rocketmq.client.producer.SendResult;
import org.apache.rocketmq.common.message.Message;
import org.apache.rocketmq.remoting.exception.RemotingException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.nio.charset.StandardCharsets;

@RequestMapping("/delayMsg")
@Controller
public class DelayMsgController {
    @Autowired
    @Qualifier("msgProducer")
    DefaultMQProducer msgProducer;

    @RequestMapping("/sync")
    @ResponseBody
    public R syncProcuder(){
        try {
//            msgProducer.start();
            for(int i = 0; i < 2; i++){
                Message mQMsg = new Message();
                mQMsg.setTopic("delayTopic");
                mQMsg.setDelayTimeLevel(3);
                byte[] body = ("Hi" + i).getBytes(StandardCharsets.UTF_8);
                mQMsg.setBody(body);
                SendResult sendResult = msgProducer.send(mQMsg);
                System.out.println(sendResult);
            }
            return R.ok();
        } catch (MQClientException | MQBrokerException | RemotingException | InterruptedException e) {
            e.printStackTrace();
            return R.error(e.getMessage());
        }finally {
//            msgProducer.shutdown();
        }
    }
}
